package com.xiaoxi.common.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoxi.domain.user.BMSUserContext;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @ClassName JwtTokenUtils
 * @Description 验证 和 生成 jwtToken
 * @Author xiaoxi
 * @Date 2022/4/24 15:56
 * @Version 1.0
 */
@Slf4j
public class JwtTokenUtils {

    // 密钥
    private static final String secret = "xiaoxi-secret";
    // 过期时间
    private static final Long expiration = 86400L;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 根据用户信息生成Token
     * 服务端是可以不用保存 Token 的，只需要客户端保存即可
     * @return token
     */
    public static String generateToken(BMSUserContext bmsUserContext) {
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("bmsUserContext", bmsUserContext);
        return generateToken(claims);
    }

    /**
     * 从Token中获取存储内容
     *
     * @param token token
     * @return 用户名
     */
    public static BMSUserContext getUserToken(String token) {
        Claims claims = getClaimsFromToken(token);
        if(Objects.isNull(claims)) {
            return null;
        }
        return objectMapper.convertValue(claims.get("bmsUserContext"),BMSUserContext.class);
    }

    /**
     * 从Token中获取荷载
     *
     * @param token
     * @return
     */
    public static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("token无效:{}",token);
            return null;
        }
        return claims;
    }

    /**
     * 判断Token是否失效
     *
     * @param token
     * @return
     */
    public static boolean isTokenExpired(String token) {
        Date expireDate = getExpiredDateFromToken(token);
        return expireDate.before(new Date());
    }

    /**
     * 从Token中获取过期时间
     *
     * @param token
     * @return
     */
    public static Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    /**
     * 根据荷载生成JWT Token
     *
     * @param claims
     * @return
     */
    public static String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 生成Token失效时间
     *
     * @return
     */
    public static Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }
}

